// https://leetcode.cn/problems/print-foobar-alternately/
// Created by ade on 2022/11/2.
// 两个线程A和B，分别交替打印foo和bar

class FooBar {
private:
    int n;
    pthread_mutex_t ta,tb;

public:
    FooBar(int n) {
        this->n = n;
        pthread_mutex_init(&ta, NULL);
        pthread_mutex_init(&tb, NULL);
        pthread_mutex_lock(&ta);
    }

    void foo(function<void()> printFoo) {
        for (int i = 0; i < n; i++) {
            pthread_mutex_lock(&tb);
            // printFoo() outputs "foo". Do not change or remove this line.
            printFoo();
            pthread_mutex_unlock(&ta);
        }
    }

    void bar(function<void()> printBar) {
        for (int i = 0; i < n; i++) {
            pthread_mutex_lock(&ta);
            // printBar() outputs "bar". Do not change or remove this line.
            printBar();
            pthread_mutex_unlock(&tb);
        }
    }
};